#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import pymongo
from pymongo import MongoClient
# import random


class MongoStore(object):

    def __init__(self, client=None):
        # if a client object is not passed
        # then try connecting to mongodb at the default localhost port
        self.client = MongoClient(
            'localhost', 27017, connect=False) if client is None else client
        self.db = self.client.proxy
        self.proxys = self.db.proxys

    def drop_db(self):
        self.client.drop_database(self.db)

    def delete(self, conditions):
        '''conditions must be a list and items required to be tuple
        >>> conditions = [('protocol': 1), ('types': 0)]
        '''
        if conditions:
            self.proxys.delete_one(dict(conditions))
        else:
            pass

    def select(self, count=None, conditions=None):
        if count:
            count = int(count)
        else:
            count = 0
        if conditions:
            conditions = dict(conditions)
            conditions_name = ['types', 'protocol']
            for condition_name in conditions_name:
                value = conditions.get(condition_name, None)
                if value:
                    conditions[condition_name] = int(value)
        else:
            conditions = {}
        items = self.proxys.find(conditions, limit=count).sort(
            [("speed", pymongo.ASCENDING), ("score", pymongo.DESCENDING)])
        results = []
        for item in items:
            result = (item['ip'], item['port'], item['protocol'])
            results.append(result)
        return results

    def close(self):
        self.client.close()

    def clear(self):
        self.db.drop()


def get_ipproxies(count=20, country='国内'):
    db = MongoStore()
    results = db.select(count, conditions=[('country', country)])
    if not results:
        results = db.select(count, conditions=[('country', '国外')])
    if results:
        proxies = map(
            lambda x: 'https://' + x[0] + ':' + str(x[1]) if x[2] == 1 else 'http://' + x[0] + ':' + str(x[1]), results)
        return map(lambda x: (x.split(':')[0], x), proxies)
    else:
        print 'no ip proxy, spider stopped'
        sys.exit()

# test
# print get_ipproxies()
# print len(get_ipproxies())
